import req from "../req.js"
import cfg from "../config.js"
import utils from "../utils.js"

//修改默认请求格式与后台匹配
function requestAdaptor(api, ignores) {
    let data = api.data;
    api.data = {
      filter: []
    }
    let keys = Object.keys(data);
    for (let key of keys) {
      if (key == 'page') {
        api.data.page = data.page;
      }
      else if (key == 'perPage') {
        api.data.perpage = data.perPage;
      }
      else if (key == 'orderBy') {
        api.data.orderby = data.orderBy;
      }
      else if (key == 'orderDir') {
        api.data.orderdir = data.orderDir;
      }
      else if (key == 'keywords') {
        api.data.keywords = data.keywords;
      }
      else {
        api.data.filter.push({
          key: key,
          value: data[key],
          like: true
        })
      }
    }
    return api;
  }

let page_type = {
    open: async function (page_info,extension) {
        let page_html_id=page_info.page_html_id;
        let property=page_info.property;
        let ext_js=page_info.ext_js;
        let page_id=page_info.page_id;
        let rights=page_info.rights;
        let params=page_info.params;
        $("#" + page_html_id).addClass("form-page row");
        $("#" + page_html_id).html("\
        <div class='col-md-8 col-sm-12 col-xs-12' style='padding-left:0.5rem;padding-right:0.5rem;'>\
            <div class='view-part form-view-part'></div>\
        </div>");

        let datamodel = property.datamodel;
        let tablename = property.tablename;
        let data = property.page;
        let controls = data.controls;
        let hide_submit_button = property.hide_submit_button;
        let add_form_controls = page_type.build_form_controls(controls);
        if(extension && extension.after_build_form_controls) extension.after_build_form_controls(add_form_controls);
        let viewJSON =
        {
            "type": "page",
            "body": [
                {
                    "type": "html",
                    "html": (data.title ? "<center><h1>" + data.title + "</h1></center>" : "") + (data.subtitle ? "<center><h4>" + data.subtitle + "</h4></center>" : "")
                },
                {
                    "type": "form",
                    "name": "form",
                    "title": "",
                    "resetAfterSubmit": true,
                    "mode": "normal",
                    "api": {
                        "method": "post",
                        "url": cfg.api_server + "datamodel/add",
                        "requestAdaptor": function (api) {
                            let newrow = api.data;
                            utils.handlepassword(newrow, property.columns);
                            api.data = {
                                rows: [newrow]
                            }
                            api.data.datamodel = datamodel;
                            api.data.tablename = tablename;
                        }
                    },
                    "controls": add_form_controls,
                    "actions": [
                        hide_submit_button?{}:
                        {
                          "type": "submit",
                          "label": "提交",
                          "icon": "fa fa-check",
                          "level": "primary",
                          "feedback": {
                            "title": "成功",
                            "body": "已成功提交数据！",
                            "actions": [
                                {
                                  "type": "button",
                                  "actionType": "confirm",
                                  "label": "确认",
                                  "className": "form-success-confirm-button",
                                  "primary": true
                                }
                              ]
                          }
                        }
                    ]
                },
                {
                    "type": "html",
                    "html": data.description ? "<span>" + data.description + "</span>" : ""
                }
            ]
        }
        if(extension && extension.after_build_amis_json) extension.after_build_amis_json(viewJSON);
        let form_data={};
        if(extension && extension.form_instance_id){
            let params = {
                datamodel: datamodel,
                tablename: tablename,
                id: extension.form_instance_id
            }
            form_data = await req("datamodel/getrow", params) //form data
        }
        let amis = amisRequire('amis/embed');
        let view_amisScoped = amis.embed(
            '#' + page_html_id + " .form-view-part", viewJSON, {data:form_data},
            {
                theme: 'antd'
            }
        );
    },
    build_form_controls : function (controls) {
        if (!controls) return [];
        let add_form_controls = [];
        let add_form_controls_group = [];
        for (let c of controls) { //all fields
            let name = c.field_name;
            let label = c.name;
            let type = c.type;
            let add_form_control = {
                type: "text",
                name: name,
                label: label,
                required: c.required
            }
            if (type == "textarea") {
                add_form_control.type = "textarea";
            }
            else if (type == "number") {
                add_form_control.type = "input-number";
            }
            else if (type == "date") {
                add_form_control.type = "input-date";
            }
            else if (type == "datetime") {
                add_form_control.type = "input-datetime";
            }
            else if (type == "switch") {
                add_form_control.type = "switch";
            }
            else if (type == "password") {
                add_form_control.type = "input-password";
            }
            else if (type == "select") { //下拉选框
                add_form_control.type = "select";
            }
            else if (type == "file") { //文件上传
                add_form_control.type = "input-file";
                add_form_control.receiver = cfg.file_server+"upload/";
            }
            else if (type == "image") { //图片上传
                add_form_control.type = "input-image";
                add_form_control.receiver = cfg.file_server+"upload/";
            }
            else if (type == "radios") { //单选列表
                add_form_control.type = "radios";
                add_form_control.options = c.options;
            }
            else if (type == "checkboxes") { //多选列表
                add_form_control.type = "checkboxes";
                add_form_control.options = c.options;
            }
            else if (type == "related") { //关联表选择
                let related_set = c.select_type=="select" ? {
                    "type": "tree-select",
                    "searchable": true,
                    "onlyChildren": true,
                    "showIcon": false,
                    "source": {
                        "method": "post",
                        "url": cfg.api_server + "tree/build",
                        "data": { tree: [
                            {
                                "table_name": c.related_table,
                                "this_field": c.that_field,
                                "label_field": c.that_label_field
                            }
                        ] }
                    }
                }
                    :
                    {
                        "type": "picker",
                        "source": {
                            "method": "post",
                            "url": cfg.api_server + "datamodel/getrows",
                            "requestAdaptor": function (api) {
                                if (api.data.op == "loadOptions") {
                                    let option_value = api.data.value;
                                    api.data = {
                                        filter: [{ key: c.that_field, value: option_value, like: false }]
                                    }
                                }
                                else {
                                    requestAdaptor(api);
                                }
                                api.data.datamodel = c.related_datamodel;
                                api.data.tablename = c.related_table;
                            }
                        },
                        "valueField": c.that_field,
                        "labelField": c.that_label_field,
                        "size": "md",
                        "pickerSchema": {
                            "mode": "table",
                            "affixHeader": false,
                            "syncLocation": false,
                            "perPage": 10,
                            "name": "thelist",
                            "columns": [
                                {
                                    "name": c.that_field,
                                    "label": c.name,
                                    "sortable": true
                                },
                                {
                                    "name": c.that_label_field,
                                    "label": c.name,
                                    "searchable": true,
                                    "sortable": true
                                }
                            ]
                        }
                    };
                add_form_control = {
                    ...add_form_control,
                    ...related_set
                }
    
            }
            else if (type == "fieldSet") { //分组容器
                add_form_control.type = "fieldSet";
                add_form_control.title = label;
                add_form_control.collapsable = true;
                add_form_control.body = build_form_controls(c.body);
            }
            //新增窗口的分组处理
            let group_no = c.group_no;
            if (group_no) {
                if (!add_form_controls_group[group_no]) {
                    add_form_controls_group[group_no] = [];
                }
                add_form_controls_group[group_no].push(add_form_control);
            }
            else {
                let group_no = "not_in_group_" + Math.random();
                add_form_controls_group[group_no] = [add_form_control];
            }
    
        }
        //对添加窗口的分组处理
        for (let group_controls of Object.values(add_form_controls_group)) {
            let group = {
                "type": "group",
                "controls": group_controls
            };
            add_form_controls.push(group);
        }
        return add_form_controls;
    }
}

export default page_type;